// 初始化配置页面
document.addEventListener("DOMContentLoaded", initOptions);

async function initOptions() {
  const ruleList = document.getElementById("ruleList");
  const addBtn = document.getElementById("addRule");
  const saveBtn = document.getElementById("saveRules");

  // 加载存储的规则
  const { rules = [] } = await chrome.storage.local.get("rules");
  renderRules(rules);

  addBtn.addEventListener("click", () => {
    rules.push({ name: "", pattern: "" });
    renderRules(rules);
  });

  saveBtn.addEventListener("click", async () => {
    const inputs = ruleList.querySelectorAll("input");
    rules.forEach((rule, index) => {
      rule.name = inputs[index * 2].value;
      rule.pattern = inputs[index * 2 + 1].value;
    });
    await chrome.storage.local.set({ rules });
    alert("配置已保存");
  });
}

function renderRules(rules) {
  const ruleList = document.getElementById("ruleList");
  ruleList.innerHTML = "";
  rules.forEach((rule, index) => {
    const div = document.createElement("div");
    div.className = "rule-item";
    div.innerHTML = `
      <input type="text" placeholder="规则名称" value="${rule.name}">
      <input type="text" placeholder="匹配模式" value="${rule.pattern}">
      <button class="btn danger" data-index="${index}">删除</button>
    `;

    div.querySelector(".danger").addEventListener("click", () => {
      rules.splice(index, 1);
      renderRules(rules);
      chrome.storage.local.set({ rules });
    });

    ruleList.appendChild(div);
  });
}

// 暴露方法给全局对象
window.updateRuleName = async (index, value) => {
  const { rules = [] } = await chrome.storage.local.get("rules");
  rules[index].name = value;
  chrome.storage.local.set({ rules });
};

window.updateRulePattern = async (index, value) => {
  const { rules = [] } = await chrome.storage.local.get("rules");
  rules[index].pattern = value;
  chrome.storage.local.set({ rules });
};
